$(function(){
    initSearchForm();
})

function initSearchForm() {
    var form  = $('#search-form');
    var input = form.find('input[type=text]');

    input.keyup(function(){
        var to = $(this).data('timeout');
        if (to) {
            clearTimeout(to);
        }
        input.removeClass('loading');
        $(this).data('timeout', setTimeout(function(){
            doSearch(input);
        }, 800));
    });
}

function doSearch(input) {
    var kword = input.val();
    $.ajax({
        url: '/search',
        type: 'post',
        data: {keyword: kword, limit: 10, ajax: 1},
        beforeSend: function(){
            input.addClass('loading').removeClass('search');
        },
        complete: function(req) {
            input.removeClass('loading');
            if (req.status == 200) {
                response = JSON.parse(req.responseText);
                showSearchResults(kword, response);
            }
        }
    });
}

function showSearchResults(kword, response) {
    var input   = $('#search-form input[type=text]');
    var ul      = $('#search-form ul');
    var results = response.results;
    var total   = response.total;
    var count   = response.count;
    ul.empty();

    if (total > 0) {
        input.addClass('search');
    } else {
        input.removeClass('search');
    }

    var brand, model;
    for (x in results) {
        model = results[x];
        brand = model.brand;

        $('<li>')
            .appendTo(ul)
            .append(
                $('<a>')
                    .html(brand.name+" "+model.name)
                    .attr('href', '/m/'+brand.name+'/'+model.id+'/'+model.name)
                    .prepend('<img align="right" src="/img/models/'+brand.name+'/'+model.name+'.jpg" height="36">')
                    .append('<br clear="all">')
            );
    }

    if (total > count) {
        ul.append('<li class="more"><a href="/search/'+kword+'">svi rezultati...</a></li>');
    }
}